/**
 * File    : Login.java
 * Created : 2008-9-5
 * By      : LuHuiguo
 */
package com.luhuiguo.sso.tutorial.pages;

import org.apache.tapestry5.Link;
import org.apache.tapestry5.annotations.CleanupRender;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.internal.services.ComponentInvocationImpl;
import org.apache.tapestry5.internal.services.LinkImpl;
import org.apache.tapestry5.internal.services.OpaqueConstantTarget;
import org.apache.tapestry5.internal.services.RequestPathOptimizer;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Response;

/**
 * @author LuHuiguo
 * @version $Id: Login.java 2 2008-10-04 13:04:21Z LuHuiguo $
 * 
 */
public class Login {
	@Inject
	private Request request;

	@Inject
	private Response response;

	@Inject
	private Messages messages;

	@Inject
	private RequestPathOptimizer optimizer;

	private String username;

	@Component(id = "loginForm")
	private Form form;

	@OnEvent("activate")
	void onActivate(String extra) {
		if (extra.equals("failed")) {
			form.recordError(messages.get("error.login.failed"));
		}
	}

	@OnEvent("success")
	Link onSuccess() {
		Link link = new LinkImpl(response, optimizer, null, request
				.getContextPath(), new ComponentInvocationImpl(
				new OpaqueConstantTarget("j_spring_openid_security_check"),
				new String[0], null), false);

		String openIdUsername = messages.get("openid.prefix") + username
				+ messages.get("openid.suffix");

		link.addParameter("j_username", openIdUsername);
		return link;
	}

	@CleanupRender
	void cleanupRender() {
		form.clearErrors();
	}

	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username
	 *            the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

}
